import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_house_manager/constants/index.dart';
import 'package:flutter_house_manager/controller/build_controller.dart';
import 'package:flutter_house_manager/utils/toast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  // 存储位置信息
  String _currentAddress = "";
  bool isloading = false;
  BuildController buildController = Get.find<BuildController>();
  // 获取当前位置的详细信息
  getLocationString(double latitude, double longitude) async {
    // 1.创建Dio实例
    Dio dio = Dio();
    // 2.发起get请求
    final res = await dio.get(GlobalVariable.GAO_BASE_URL + HTTP_PATH.REGEO,
        queryParameters: {
          "key": GlobalVariable.GAO_KEY,
          "location": '$longitude,$latitude'
        });
    // 3.解析数据
    if (res.data["status"] == "1") {
      _currentAddress = res.data["regeocode"]["formatted_address"];
      setState(() {});
    } else {
      PromptAction.showError('获取定位失败');
    }
  }

  // 获取附近社区
  List _aroundList = [];
  getNearList(double latitude, double longitude) async {
    isloading = true;

    Dio dio = Dio();
    final res = await dio.get(
        '${GlobalVariable.GAO_BASE_URL}${HTTP_PATH.NEARLIST}',
        queryParameters: {
          "key": 'ec6f580a9ed57f6731978c15a3a50fb1',
          "location": '$longitude,$latitude',
          "keywords": '住宅小区公寓',
          "radius": 2000, // 米
          "offset": 10 // 限制查询的条数
        });
    if (res.data["status"] == "1") {
      _aroundList = res.data["pois"];
      setState(() {
        isloading = false;
      });
    } else {
      PromptAction.showError('获取定位失败');
    }
  }

// --------------------------------------------------------------------
  getAccess() async {
    PermissionStatus status = await Permission.location.request(); // 申请定位权限
    if (status == PermissionStatus.granted) {
      PromptAction.showSuccess("定位权限已获取");
      // 可以获取定位了
    } else {
      PromptAction.showSuccess("请去设置打开定位权限");
    }
  }

  // 获取当前位置的经纬度
  getLocation() async {
    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      PromptAction.showWarning("请去设置打开定位权限");
      return;
    }
    // 获取当前位置的经纬度
    var location = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    PromptAction.showSuccess(
        "当前位置：${location.latitude}, ${location.longitude}");
  }

  @override
  void initState() {
    super.initState();
    // getAccess(); //  申请获取地理定位的权限
    // getLocation();
    getLocationString(40.060294, 116.343367);
    getNearList(40.060294, 116.343367);
  }

  @override
  Widget build(BuildContext context) {
    if (isloading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          const Row(
            children: [
              Text(
                '当前地址',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(child: Text(_currentAddress)),
                GestureDetector(
                  onTap: () {
                    isloading = true;
                    getLocationString(40.060294, 116.343367);
                    getNearList(40.060294, 116.343367);
                  },
                  child: const Row(
                    children: [
                      Icon(Icons.location_searching_outlined,
                          color: Colors.blue),
                      SizedBox(width: 2),
                      Text(
                        '重新定位',
                        style: TextStyle(color: Colors.blue),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
          const SizedBox(height: 10),
          const Row(
            children: [
              Text(
                '附近社区',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: getAroundListWidget(),
            // [
            //   Container(
            //     color: Colors.white,
            //     padding: const EdgeInsets.all(10),
            //     child: const Row(
            //       children: [
            //         Expanded(child: Text('北京市昌平区政府街19号')),
            //         Row(
            //           children: [
            //             Icon(Icons.arrow_forward_ios,
            //                 size: 16, color: Colors.black),
            //           ],
            //         )
            //       ],
            //     ),
            //   )
            // ],
          )
        ],
      ),
    );
  }

  // 周边社区列表
  List<Widget> getAroundListWidget() {
    // 得到了一个列表
    return _aroundList.map((item) {
      return Container(
          color: Colors.white,
          padding: const EdgeInsets.all(10),
          child: GestureDetector(
            onTap: () {
              // 1.更新全局数据
              buildController.updateBuildInfo({'point': item["name"]});
              // 2.跳转楼栋列表页面
              Navigator.pushNamed(context, '/buildinglist');
            },
            child: Row(
              children: [
                Expanded(child: Text(item["name"])),
                const Row(
                  children: [
                    Icon(Icons.arrow_forward_ios,
                        size: 16, color: Colors.black),
                  ],
                )
              ],
            ),
          ));
    }).toList();
  }
}
